package com.example.petproject.service.impl;

import com.example.petproject.constants.Constants;
import com.example.petproject.entity.vo.CartProductVO;
import com.example.petproject.entity.vo.ReturnStatusEnum;
import com.example.petproject.execption.BaseException;
import com.example.petproject.mapper.PmsSkuMapper;
import com.example.petproject.service.OmsCartService;
import com.example.petproject.service.third.ali.AliYunOSSService;
import com.example.petproject.util.ObjectMapperUtils;
import com.example.petproject.util.RedisKeyUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 包名称：com.example.petproject.service.impl
 * 类名称：OmsCartServiceImpl
 * 类描述：购物车service层实现
 * 创建人：@author DrinkMore-HotWater
 * 创建时间：2024年01月17日 14:34
 **/
@Service
public class OmsCartServiceImpl implements OmsCartService {

    private static final Logger log = LoggerFactory.getLogger(OmsCartServiceImpl.class);

    @Resource
    private PmsSkuMapper pmsSkuMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AliYunOSSService aliYunOSSService;

    @Override
    public Boolean addCart(Long skuId, Integer num,Long userId) {
        try {
            //添加前先判断当前规格的商品是否在购物车中已存在，根据不同的情况执行不同的处理，如果存在，则只需要更新数量和总价，否则新增商品
            String cartKey = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_CART, String.valueOf(userId));
            //先根据当前用户ID取出对应购物车中所有的商品
            String cartVOStr=(String)stringRedisTemplate.opsForHash().get(cartKey, String.valueOf(skuId));

            CartProductVO cartProductVO = ObjectMapperUtils.stringToObj(cartVOStr, CartProductVO.class);

            //如果当前商品为空，表示当前skuId对应的商品购物车中不存在
            if (ObjectUtils.isEmpty(cartProductVO)) {
                //如果购物车中不存在对应的商品，则先根据skuId查询商品相关信息
                cartProductVO = pmsSkuMapper.selectCartProductVOBYskuId(skuId);
                if (ObjectUtils.isEmpty(cartProductVO)) {
                    log.info("skuId:{}，对应的商品不存在", skuId);
                    throw new BaseException(ReturnStatusEnum.PRODUCT_SPU_EMPTY);
                }
            }else {
                //如果购物车中已存在对应的商品，则修改商品的数量及总价
                num = num + cartProductVO.getNum();

            }
            //完善添加时间及对应用户的id
            cartProductVO.setAddTime(LocalDateTime.now());
            cartProductVO.setUserId(userId);
            cartProductVO.setNum(num);
            //同步计算挡墙规格商品的总价
            BigDecimal amountPrice = cartProductVO.getUnitPrice().multiply(BigDecimal.valueOf(num));
            cartProductVO.setPrice(amountPrice);
            //将查询出来的商品信息存入redis

            //调用序列化接口
            stringRedisTemplate.opsForHash().put(cartKey, String.valueOf(skuId), ObjectMapperUtils.objToString(cartProductVO));
            return true;
        } catch (JsonProcessingException e) {
            log.error("添加购物车异常：{}",e.getMessage());
            throw new BaseException(ReturnStatusEnum.SYSTEM_EXCEPTION);
        }
    }

    /**
     * 查询用户的购物车信息
     * @param userId 用户ID
     * @return List<CartListVO>
     */
    @Override
    public List<CartProductVO> getCartList(Long userId) {
        try {
            List<CartProductVO> cartProductVOList = new ArrayList<>();
            //先根据当前用户ID生成cartKey
            String cartKey = RedisKeyUtils.formatKeyWithPrefix(Constants.Redis.PREFIX_CART,String.valueOf(userId));
            //从redis中取出商品信息
            Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(cartKey);
            for (Object key : entries.keySet()) {
                String values = (String) entries.get(key);
                //反序列化成cartProductVO
                CartProductVO cartProductVO = ObjectMapperUtils.stringToObj(values, CartProductVO.class);
                //处理图片路径
                cartProductVO.setPicUrl(aliYunOSSService.getSymink(cartProductVO.getPicUrl()));
                cartProductVOList.add(cartProductVO);
            }
            return cartProductVOList;
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
